package com.lanou.service.impl;

import com.lanou.entity.TbContent;
import com.lanou.entity.TbContentExample;
import com.lanou.mapper.TbContentMapper;
import com.lanou.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by QuChao on 2018/11/23
 */
@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private TbContentMapper tbContentMapper;

    @Override
    public List<TbContent> list(Long categoryId) {
        TbContentExample tbContentExample = new TbContentExample();
        if (categoryId != 0) {
            tbContentExample.createCriteria().andCategoryIdEqualTo(categoryId);
        }
        return tbContentMapper.selectByExampleWithBLOBs(tbContentExample);
    }

    @Override
    public boolean save(TbContent tbContent) {
        if (tbContent != null) {
            Date date = new Date();
            tbContent.setCreated(date);
            tbContent.setUpdated(date);
            System.out.println(tbContent);
            int insert = tbContentMapper.insert(tbContent);
            if (insert == 1) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public boolean edit(TbContent tbContent) {
        if (tbContent != null) {
            TbContentExample tbContentExample = new TbContentExample();
            tbContentExample.createCriteria().andIdEqualTo(tbContent.getId());
            int i = tbContentMapper.updateByExampleWithBLOBs(tbContent, tbContentExample);
            if (i == 1) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean deleteByIds(Long[] ids) {
        if (ids.length == 0) {
            return false;
        } else {
            for (Long id : ids) {
                int i = tbContentMapper.deleteByPrimaryKey(id);
                if (i == 0) {
                    return false;
                }
            }
            return true;
        }
    }
}
